package org.example;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {

//    放行列表
    private final List<String> excludedUrls = Arrays.asList("/login", "/register", "/public");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 如果需要的话，过滤器初始化逻辑
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());

        // 检查请求路径是否在排除列表中
        if (isExcludedPath(path)) {
            System.out.println(path);
            chain.doFilter(request, response);
            return;
        }

        HttpSession session = httpRequest.getSession(false);

        // 检查用户是否已登录
        if (session != null && session.getAttribute("user") != null) {
            chain.doFilter(request, response);
            System.out.println("获取到session,用户已登录");
            System.out.println(session.getAttribute("user"));
        } else {
            System.out.println("用户未登录，跳转登录页");
            // 如果用户未登录则重定向到登录页面
            httpResponse.sendRedirect(httpRequest.getContextPath() + "/login");
        }
    }

    @Override
    public void destroy() {
        // 如果需要的话，过滤器清理逻辑
    }

    /**
     * 检查当前请求路径是否在排除列表中。
     * @param path 当前请求路径
     * @return 如果路径被排除则返回 true，否则返回 false
     */
    private boolean isExcludedPath(String path) {
        return excludedUrls.stream().anyMatch(path::startsWith);
    }
}
